import base64

from playwright.sync_api import Playwright, sync_playwright, expect


def run(playwright: Playwright) -> None:

    browser = playwright.chromium.launch(headless=False)
    context = browser.new_context()
    page = context.new_page()
    page.goto("http://www.xxxx.net:8087/ords")
    page.locator("#F4550_P1_COMPANY").fill("esun")
    page.locator("#F4550_P1_COMPANY").press("Tab")
    page.locator("#F4550_P1_USERNAME").fill("admin")
    page.locator("#F4550_P1_USERNAME").press("Tab")
    page.locator("#F4550_P1_PASSWORD").fill("gss=lx")
    page.locator("#F4550_P1_PASSWORD").press("Enter")
    page.locator("a.a-ImageNav-link.app-builder").click()
    expect(page.locator(".a-AppCards-itemContainer:has-text('161')").locator("button.launch-aut")).to_be_enabled()
    with page.expect_popup() as page1_info:
        # 这个click某些情况下不生效,click执行成功但没有产生效果
        page.locator(".a-AppCards-itemContainer:has-text('161')").locator("button.launch-aut").click()
        # page.get_by_role("cell", name="测试应用 161  ").get_by_title("Run").click()
    page1 = page1_info.value
    page1.locator("#P9999_USERNAME").fill("admin")
    page1.locator("#P9999_USERNAME").press("Tab")
    page1.locator("#P9999_PASSWORD").fill("gss=lx")
    page1.locator(".t-Login-buttons > button:has-text('登录')").click()
    page1.locator("#t_Button_navControl").click()
    page1.get_by_role("menuitem", name="样式测试").click()
    # page1.wait_for_timeout(3000)
    # 自动等待元素就位,之后再操作可保证不因元素不存在而出错
    expect(page1.locator("div#table-wrap div.t-fht-tbody table.a-IRR-table tr > td").last).to_be_enabled()
    print(page1.locator("div#table-wrap div.t-fht-tbody table.a-IRR-table tr").count())
    for i_tr in page1.locator("div#table-wrap div.t-fht-tbody table.a-IRR-table tr").all():
        if i_tr.locator("th").count() > 0:
            continue
        # print(i_tr.inner_html())
        code = i_tr.locator("td:nth-child(2)").inner_html()
        name = i_tr.locator("td:nth-child(3)").inner_html()
        xh = i_tr.locator("td:nth-child(4)").inner_html()
        if code.isspace():
            continue
        print(code+","+name+","+xh)
    print(page1.locator("div#table-wrap div.t-fht-tbody table.a-IRR-table tr > td").count())
    # page1.locator("div#table-wrap div.t-fht-tbody  table.a-IRR-table tr > td.a-IRR-linkCol.u-tC > a").first.click()
    # page1.wait_for_timeout(3000)
    # page1.screenshot(path="screenshot.png")
    print("操作结束")
    # ---------------------
    context.close()
    browser.close()


with sync_playwright() as playwright:
    run(playwright)
